<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="统计日期" prop="statDate">
        <el-date-picker clearable
          v-model="queryParams.statDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
          style="width: 150px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="统计类型" prop="statType">
        <el-select v-model="queryParams.statType" placeholder="选择类型" clearable style="width: 120px">
          <el-option label="设备" value="device"></el-option>
          <el-option label="环境" value="environment"></el-option>
          <el-option label="检测" value="detection"></el-option>
          <el-option label="告警" value="alarm"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备总数" prop="totalDevices">
        <el-input-number
          v-model="queryParams.totalDevices"
          placeholder="设备总数"
          :min="0"
          :precision="0"
          controls-position="right"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="检测精度" prop="avgDetectionAccuracy">
        <el-input-number
          v-model="queryParams.avgDetectionAccuracy"
          placeholder="精度%"
          :min="0"
          :max="100"
          :precision="2"
          controls-position="right"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="告警总数" prop="totalAlarms">
        <el-input-number
          v-model="queryParams.totalAlarms"
          placeholder="告警数"
          :min="0"
          :precision="0"
          controls-position="right"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="数据质量" prop="dataQualityScore">
        <el-input-number
          v-model="queryParams.dataQualityScore"
          placeholder="评分"
          :min="0"
          :max="100"
          :precision="2"
          controls-position="right"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dataStatisticsSummary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dataStatisticsSummary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dataStatisticsSummary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:dataStatisticsSummary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="dataStatisticsSummaryList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="summaryId" width="80" />
      <el-table-column label="统计日期" align="center" prop="statDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.statDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="statType" width="80">
        <template slot-scope="scope">
          <el-tag :type="getStatTypeTagType(scope.row.statType)" size="mini">
            {{ getStatTypeLabel(scope.row.statType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备总数" align="center" prop="totalDevices" width="90" />
      <el-table-column label="在线" align="center" prop="onlineDevices" width="70" />
      <el-table-column label="离线" align="center" prop="offlineDevices" width="70" />
      <el-table-column label="故障" align="center" prop="faultDevices" width="70" />
      <el-table-column label="检测鱼数" align="center" prop="totalFishDetected" width="100" />
      <el-table-column label="检测精度%" align="center" prop="avgDetectionAccuracy" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.avgDetectionAccuracy">{{ scope.row.avgDetectionAccuracy }}%</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="告警总数" align="center" prop="totalAlarms" width="90" />
      <el-table-column label="严重告警" align="center" prop="criticalAlarms" width="90" />
      <el-table-column label="已处理" align="center" prop="handledAlarms" width="80" />
      <el-table-column label="水温°C" align="center" prop="avgWaterTemperature" width="85">
        <template slot-scope="scope">
          <span v-if="scope.row.avgWaterTemperature">{{ scope.row.avgWaterTemperature }}°C</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="pH值" align="center" prop="avgPhValue" width="70" />
      <el-table-column label="溶解氧mg/L" align="center" prop="avgDissolvedOxygen" width="110">
        <template slot-scope="scope">
          <span v-if="scope.row.avgDissolvedOxygen">{{ scope.row.avgDissolvedOxygen }}mg/L</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="质量评分" align="center" prop="dataQualityScore" width="90">
        <template slot-scope="scope">
          <el-progress 
            v-if="scope.row.dataQualityScore"
            :percentage="scope.row.dataQualityScore" 
            :stroke-width="12"
            :show-text="false"
            :color="getQualityColor(scope.row.dataQualityScore)"
          ></el-progress>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dataStatisticsSummary:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dataStatisticsSummary:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据统计汇总对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="统计日期" prop="statDate">
              <el-date-picker clearable style="width: 100%"
                v-model="form.statDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择统计日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统计类型" prop="statType">
              <el-select v-model="form.statType" placeholder="选择统计类型" style="width: 100%">
                <el-option label="设备统计" value="device"></el-option>
                <el-option label="环境监测" value="environment"></el-option>
                <el-option label="检测分析" value="detection"></el-option>
                <el-option label="告警统计" value="alarm"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <!-- 设备相关字段 -->
          <el-col :span="24" v-if="form.statType === 'device' || form.statType === ''">
            <el-divider content-position="left">设备统计数据</el-divider>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'device' || form.statType === ''">
            <el-form-item label="设备总数" prop="totalDevices">
              <el-input-number v-model="form.totalDevices" :min="0" :precision="0" style="width: 100%" placeholder="设备总数" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'device' || form.statType === ''">
            <el-form-item label="在线设备数" prop="onlineDevices">
              <el-input-number v-model="form.onlineDevices" :min="0" :precision="0" style="width: 100%" placeholder="在线设备数" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'device' || form.statType === ''">
            <el-form-item label="离线设备数" prop="offlineDevices">
              <el-input-number v-model="form.offlineDevices" :min="0" :precision="0" style="width: 100%" placeholder="离线设备数" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'device' || form.statType === ''">
            <el-form-item label="故障设备数" prop="faultDevices">
              <el-input-number v-model="form.faultDevices" :min="0" :precision="0" style="width: 100%" placeholder="故障设备数" />
            </el-form-item>
          </el-col>
          
          <!-- 检测相关字段 -->
          <el-col :span="24" v-if="form.statType === 'detection' || form.statType === ''">
            <el-divider content-position="left">检测分析数据</el-divider>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'detection' || form.statType === ''">
            <el-form-item label="检测鱼类总数" prop="totalFishDetected">
              <el-input-number v-model="form.totalFishDetected" :min="0" :precision="0" style="width: 100%" placeholder="检测鱼类总数" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'detection' || form.statType === ''">
            <el-form-item label="平均检测精度%" prop="avgDetectionAccuracy">
              <el-input-number v-model="form.avgDetectionAccuracy" :min="0" :max="100" :precision="2" style="width: 100%" placeholder="0-100" />
            </el-form-item>
          </el-col>
          
          <!-- 告警相关字段 -->
          <el-col :span="24" v-if="form.statType === 'alarm' || form.statType === ''">
            <el-divider content-position="left">告警统计数据</el-divider>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'alarm' || form.statType === ''">
            <el-form-item label="告警总数" prop="totalAlarms">
              <el-input-number v-model="form.totalAlarms" :min="0" :precision="0" style="width: 100%" placeholder="告警总数" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'alarm' || form.statType === ''">
            <el-form-item label="严重告警数" prop="criticalAlarms">
              <el-input-number v-model="form.criticalAlarms" :min="0" :precision="0" style="width: 100%" placeholder="严重告警数" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'alarm' || form.statType === ''">
            <el-form-item label="已处理告警数" prop="handledAlarms">
              <el-input-number v-model="form.handledAlarms" :min="0" :precision="0" style="width: 100%" placeholder="已处理告警数" />
            </el-form-item>
          </el-col>
          
          <!-- 环境相关字段 -->
          <el-col :span="24" v-if="form.statType === 'environment' || form.statType === ''">
            <el-divider content-position="left">环境监测数据</el-divider>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'environment' || form.statType === ''">
            <el-form-item label="平均水温°C" prop="avgWaterTemperature">
              <el-input-number v-model="form.avgWaterTemperature" :min="0" :max="50" :precision="2" style="width: 100%" placeholder="0-50°C" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'environment' || form.statType === ''">
            <el-form-item label="平均pH值" prop="avgPhValue">
              <el-input-number v-model="form.avgPhValue" :min="0" :max="14" :precision="2" style="width: 100%" placeholder="0-14" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.statType === 'environment' || form.statType === ''">
            <el-form-item label="平均溶解氧mg/L" prop="avgDissolvedOxygen">
              <el-input-number v-model="form.avgDissolvedOxygen" :min="0" :max="20" :precision="2" style="width: 100%" placeholder="0-20mg/L" />
            </el-form-item>
          </el-col>
          
          <!-- 数据质量评分 -->
          <el-col :span="24">
            <el-divider content-position="left">数据质量</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据质量评分" prop="dataQualityScore">
              <el-slider 
                v-model="form.dataQualityScore" 
                :min="0" 
                :max="100" 
                :step="0.1"
                show-input
                :format-tooltip="formatQualityTooltip"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDataStatisticsSummary, getDataStatisticsSummary, delDataStatisticsSummary, addDataStatisticsSummary, updateDataStatisticsSummary } from "@/api/system/dataStatisticsSummary";

export default {
  name: "DataStatisticsSummary",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据统计汇总表格数据
      dataStatisticsSummaryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        statDate: null,
        statType: null,
        totalDevices: null,
        onlineDevices: null,
        offlineDevices: null,
        faultDevices: null,
        totalFishDetected: null,
        avgDetectionAccuracy: null,
        totalAlarms: null,
        criticalAlarms: null,
        handledAlarms: null,
        avgWaterTemperature: null,
        avgPhValue: null,
        avgDissolvedOxygen: null,
        dataQualityScore: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        statDate: [
          { required: true, message: "统计日期不能为空", trigger: "blur" }
        ],
        statType: [
          { required: true, message: "统计类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据统计汇总列表 */
    getList() {
      this.loading = true;
      listDataStatisticsSummary(this.queryParams).then(response => {
        this.dataStatisticsSummaryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        summaryId: null,
        statDate: null,
        statType: null,
        totalDevices: null,
        onlineDevices: null,
        offlineDevices: null,
        faultDevices: null,
        totalFishDetected: null,
        avgDetectionAccuracy: null,
        totalAlarms: null,
        criticalAlarms: null,
        handledAlarms: null,
        avgWaterTemperature: null,
        avgPhValue: null,
        avgDissolvedOxygen: null,
        dataQualityScore: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.summaryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据统计汇总";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const summaryId = row.summaryId || this.ids
      getDataStatisticsSummary(summaryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据统计汇总";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.summaryId != null) {
            updateDataStatisticsSummary(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDataStatisticsSummary(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const summaryIds = row.summaryId || this.ids;
      this.$modal.confirm('是否确认删除数据统计汇总编号为"' + summaryIds + '"的数据项？').then(function() {
        return delDataStatisticsSummary(summaryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dataStatisticsSummary/export', {
        ...this.queryParams
      }, `dataStatisticsSummary_${new Date().getTime()}.xlsx`)
    },
    /** 获取统计类型标签样式 */
    getStatTypeTagType(statType) {
      const typeMap = {
        'device': 'primary',
        'environment': 'success', 
        'detection': 'warning',
        'alarm': 'danger'
      };
      return typeMap[statType] || '';
    },
    /** 获取统计类型显示标签 */
    getStatTypeLabel(statType) {
      const labelMap = {
        'device': '设备',
        'environment': '环境',
        'detection': '检测', 
        'alarm': '告警'
      };
      return labelMap[statType] || statType;
    },
    /** 获取质量评分颜色 */
    getQualityColor(score) {
      if (score >= 90) return '#67c23a';
      if (score >= 80) return '#e6a23c';
      if (score >= 70) return '#f56c6c';
      return '#909399';
    },
    /** 格式化质量评分提示 */
    formatQualityTooltip(value) {
      if (value >= 90) return `优秀 ${value}`;
      if (value >= 80) return `良好 ${value}`;
      if (value >= 70) return `一般 ${value}`;
      return `较差 ${value}`;
    }
  }
};
</script>

<style scoped>
/* 优化表格样式 */
.common-table {
  font-size: 13px;
}

.common-table .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 优化数值显示 */
.common-table .el-table__cell {
  padding: 8px 0;
}

/* 统计类型标签样式 */
.el-tag {
  font-weight: 500;
}

/* 进度条样式 */
.el-progress {
  margin: 0 5px;
}

/* 表单优化 */
.el-form-item {
  margin-bottom: 18px;
}

.el-divider {
  margin: 15px 0;
}

.el-divider__text {
  font-weight: 600;
  color: #409eff;
}

/* 搜索表单优化 */
.el-form--inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 数字输入框优化 */
.el-input-number {
  width: 100%;
}

.el-input-number .el-input__inner {
  text-align: center;
}

/* 滑块样式优化 */
.el-slider {
  margin-bottom: 10px;
}
</style>
